<?php

Yii::import('application.modules.nosey.models._base.BaseField');

class Field extends BaseField {

    const FIELD_TYPE_TEXT = 1;
    const FIELD_TYPE_SIMPLE = 2;
    const FIELD_TYPE_MULTIPLE = 3;
    const FIELD_TYPE_BOOLEAN = 4;
    const FIELD_TYPE_DATE = 5;
    const FIELD_TYPE_RATING = 6;
    const WIDGET_TYPE_TEXT = 1;
    const WIDGET_TYPE_TEXTAREA = 2;
    const WIDGET_TYPE_RADIO = 3;
    const WIDGET_TYPE_CHECKBOX = 4;
    const WIDGET_TYPE_SELECT = 5;
    const WIDGET_TYPE_STAR_RATING = 6;
    const VALIDATION_TYPE_REQUIRED = 'required';
    const VALIDATION_TYPE_NUMERICAL = 'numerical';
    const VALIDATION_TYPE_DIGITS = 'digits';
    const VALIDATION_TYPE_EMAIL = 'email';
    const VALIDATION_TYPE_URL = 'url';

    /**
     * @return Field
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public static function label($n = 1) {
        return Yii::t('noseyModule.app', 'Field|Fields', $n);
    }

    public function getFieldTypes() {
        return array(
            self::FIELD_TYPE_TEXT => Yii::t('noseyModule.app', 'Text'),
            self::FIELD_TYPE_SIMPLE => Yii::t('noseyModule.app', 'Simple Choice'),
            self::FIELD_TYPE_MULTIPLE => Yii::t('noseyModule.app', 'Multiple Choice'),
            self::FIELD_TYPE_BOOLEAN => Yii::t('noseyModule.app', 'Boolean'),
            self::FIELD_TYPE_DATE => Yii::t('noseyModule.app', 'Date'),
            self::FIELD_TYPE_RATING => Yii::t('noseyModule.app', 'Rating'),
        );
    }

    public function getChoiceFieldTypes() {
        return array(
            self::FIELD_TYPE_SIMPLE => Yii::t('noseyModule.app', 'Simple Choice'),
            self::FIELD_TYPE_MULTIPLE => Yii::t('noseyModule.app', 'Multiple Choice'),
        );
    }

    /**
     * @return string the status text display for the current issue
     */
    public function getFieldTypeText() {
        $fieldTypes = $this->fieldTypes;
        return isset($fieldTypes[$this->field_type]) ? $fieldTypes[$this->field_type] : "unknown field_type ({$this->field_type})";
    }

    public function generatePieReport($inicio, $fin) {

        $inicio = DateTime::createFromFormat('d/m/Y', $inicio);
        $fin = DateTime::createFromFormat('d/m/Y', $fin)->modify('+1 day');
        $report = array();
        $report['title']['text'] = $this->label;
        $report['credits']['enabled'] = false;

        $report['plotOptions'] = array(
            'pie' => array(
                'allowPointSelect' => true,
                'cursor' => 'pointer',
                'dataLabels' => array(
                    'enabled' => false,
                    'format' => '<b>{point.name}</b>: {point.percentage:.1f} %'
                ),
                'showInLegend' => true,
                'tooltip' => array(
                    'pointFormat' => 'Porcentaje: <b>{point.percentage:.1f}%</b><br>{series.name}: <b>{point.y}</b>'
                ),
            )
        );
        $report['series'] = array();
        switch ($this->field_type) {
            case self::FIELD_TYPE_SIMPLE:
                $options = Yii::app()->db->createCommand()
                        ->select('nso.label, count(*) as count')
                        ->from('nosey_field_value nfv')
                        ->join('nosey_answer na', 'na.id = nfv.answer_id')
                        ->leftJoin('nosey_option nso', 'nso.id = nfv.content')
                        ->where('nfv.field_id=:field_id and na.creation_date between :inicio and :fin', array(':field_id' => $this->id, ':inicio' => $inicio->format('Y-m-d'), ':fin' => $fin->format('Y-m-d')))
                        ->order('content')
                        ->group('content')
                        ->queryAll();
                $series = array(
                    'type' => 'pie',
                    'name' => 'Cantidad',
                    'data' => array()
                );
                foreach ($options as $option) {
                    $series['data'][] = array($option['label'] ? $option['label'] : 'Sin respuesta', (int) $option['count']);
                }

                $report['series'][] = $series;

                return $report;
                break;

            case self::FIELD_TYPE_MULTIPLE:
                $options = Yii::app()->db->createCommand()
                        ->select('content')
                        ->from('nosey_field_value nfv')
                        ->join('nosey_answer na', 'na.id = nfv.answer_id')
                        ->where('nfv.field_id=:field_id and na.creation_date between :inicio and :fin', array(':field_id' => $this->id, ':inicio' => $inicio->format('Y-m-d'), ':fin' => $fin->format('Y-m-d')))
                        ->queryAll();
                $contador = array();
                foreach ($options as $answer) {

                    $temp = json_decode($answer['content']);
                    if (!empty($temp)) {
                        foreach ($temp as $opcion) {
                            if (array_key_exists($opcion, $contador)) {
                                $contador[$opcion] = ++$contador[$opcion];
                            } else {
                                $contador[$opcion] = 1;
                            }
                        }
                    } else {

                        if (array_key_exists('sin_respuesta', $contador)) {
                            $contador['sin_respuesta'] = ++$contador['sin_respuesta'];
                        } else {
                            $contador['sin_respuesta'] = 1;
                        }
                    }
                }
                $series = array(
                    'type' => 'pie',
                    'name' => 'Cantidad',
                    'data' => array()
                );
                foreach ($contador as $key => $value) {
                    if ($key != 'sin_respuesta') {
                        $key= Option::model()->findByPk($key)? Option::model()->findByPk($key)->label:'';
                    }
                    $series['data'][] = array(Util::setName($key), (int) $value);
                }

                $report['series'][] = $series;

                return $report;
                break;
            case self::FIELD_TYPE_BOOLEAN:
                $options = Yii::app()->db->createCommand()
                        ->select('content, count(*) as count')
                        ->from('nosey_field_value nfv')
                        ->join('nosey_answer na', 'na.id = nfv.answer_id')
                        ->where('field_id=:field_id and na.creation_date between :inicio and :fin', array(':field_id' => $this->id, ':inicio' => $inicio->format('Y-m-d'), ':fin' => $fin->format('Y-m-d')))
                        ->order('content')
                        ->group('content')
                        ->queryAll();

                $series = array(
                    'type' => 'pie',
                    'name' => 'Cantidad',
                    'data' => array()
                );
                foreach ($options as $option) {
                    $series['data'][] = array($option['content'] == 0 ? 'No' : 'Si', (int) $option['count']);
                }
                $report['series'][] = $series;

                return $report;
                break;
            case self::FIELD_TYPE_RATING:
                $options = Yii::app()->db->createCommand()
                        ->select('content, count(*) as count')
                        ->from('nosey_field_value nfv')
                        ->join('nosey_answer na', 'na.id = nfv.answer_id')
                        ->where('field_id=:field_id and na.creation_date between :inicio and :fin', array(':field_id' => $this->id, ':inicio' => $inicio->format('Y-m-d'), ':fin' => $fin->format('Y-m-d')))
                        ->order('content')
                        ->group('content')
                        ->queryAll();

                $series = array(
                    'type' => 'pie',
                    'name' => 'Cantidad',
                    'data' => array()
                );
                foreach ($options as $option) {
                    $series['data'][] = array($option['content']? $option['content'] : 'Sin respuesta', (int) $option['count']);
                }
                $report['series'][] = $series;

                return $report;
                break;
            default:
                break;
        }
    }

}
